import React, { Component } from 'react'
import AdvancedTable from 'components/advanced-table'
import { messages, queryCurrencyPrecision } from "share/common";
import moment from "moment";
import { Button, Popover, Radio, Tag, Input, message } from "antd";
import 'styles/request/request.scss';
import constants from "share/constants";
import { connect } from "react-redux";
import menuRoute from "routes/menuRoute";
import borrowService from 'containers/loan-billing/borrow-and-return.service';
import Stations from "components/template/proxies/stations";
import Proxies from "components/template/proxies/proxies";
import Condition from 'components/condition';
import Importer from "components/template/importer/index";
import debounce from "lodash.debounce";
const { If } = Condition;
const Search = Input.Search;
import openSlideFrame from "share/openSlideFrame";
import Space from "components/space";

class MyLoan extends Component {

  loanStatus = [{
    label: messages('common.all')/*全部*/,
    value: '10011002100310041005100610071008'
  }].concat(...constants.loanStatus);

  isNeedImporter = this.checkFunctionProfiles('loanline.excel.import.enable',[true]);

  constructor(props) {
    super(props);
    this.state = {
      columns: [
        {
          title: messages('common.submit.date')/*提交日期*/, dataIndex: 'createdDate',
          render: (value) => moment(value).format('YYYY-MM-DD'), sorter: true
        },
        {
          title: messages('common.applicant')/*申请人*/, dataIndex: 'applicantName'
        },
        {
          title: messages('common.document.name')/*单据名称*/, dataIndex: 'formName',
          render: value => <Popover placement="topLeft" content={value || '-'}>{value || '-'}</Popover>
        },
        {
          title: messages('common.document.code')/*单号*/, dataIndex: 'businessCode'
        },
        {
          title: messages('finance-1.key87')/*事由说明temp*/, dataIndex: 'title',
          render: value => <Popover placement="topLeft" content={value || '-'}>{value || '-'}</Popover>
        },
        {
          title: messages('common.currency')/*币种*/, dataIndex: 'currencyCode'
        },
        {
          title: messages('common.amount')/*金额*/, dataIndex: 'currencyAmount', align: 'right',
          render: (value,record) => this.filterMoney(value,queryCurrencyPrecision(record.currencyCode))
        },
        {
          title: messages('finance-1.key88')/*本币币种*/, dataIndex: 'baseCurrencyCode'
        },
        {
          title: messages('finance-1.key89')/*本币金额*/, dataIndex: 'baseCurrencyAmount', align: 'right',
          render: (value,record) => [1005,1006,1007].indexOf(record.status) > -1 ? this.filterMoney(value,queryCurrencyPrecision(record.baseCurrencyCode)) : '-'
        },
        {
          title: messages('common.column.status')/*状态*/, dataIndex: 'status',
          render: (value,record) => <Tag color={
            constants.getTextByValue(String(value + '' + 2005), 'documentStatus', 'color') ||
            constants.getTextByValue(String(value + '' + record.rejectType), 'documentStatus', 'color') ||
            constants.getTextByValue(String(value), 'documentStatus', 'color')
          }>{
            constants.getTextByValue(String(value + '' + 2005), 'documentStatus') ||
            constants.getTextByValue(String(value + '' + record.rejectType), 'documentStatus') ||
            constants.getTextByValue(String(value), 'documentStatus')
          }</Tag>
        }
      ],
      searchForm: [
        {
          id: 'formOIDs', label: messages('common.document.name')/*单据名称*/, component: 'Selector',
          props: {
            type: 'proxyForm',
            params: { formType: 104, isAll: true }
          },
          parser: value => value ? { formOIDs: [value] } : null,
          dataIndex: 'formName'
        },
        {
          id: 'dateRange', component: 'DateRangePicker', label: messages('common.submit.date')/*提交日期*/,
          parser: value => ({
            startDate: value && value[0] ? moment(value[0]).format('YYYY-MM-DD 00:00:00') : null,
            endDate: value && value[1] ? moment(value[1]).format('YYYY-MM-DD 23:59:59') : null
          }),
          dataIndex: 'createdDate'
        },
        {
          id: 'applicantOIDs', label: messages('finance-1.key90')/*申请人姓名/工号*/, component: 'Selector',
          props: {
            placeholder: messages('common.please.input')/*请输入*/ + messages('finance-1.key90')/*申请人姓名/工号*/,
            selectorItem: {
              key: 'userOID',
              searchKey: 'keyword',
              url: `/api/users/v3/search?page=0&size=9999&roleType=TENANT&status=all`,
              label: record => (`${record.employeeID}-${record.fullName}${(record.status !== 1001 ?
                  (`（${record.status === 1002 ?
                      messages('finance-1.key91')/*待离职员工*/ :
                      messages('finance-1.key92')/*离职员工*/}）`
                  ) :
                  ''
              )}`)
            },
            searchIfKeywordIsNull: true
          },
          parser: value => value ? { applicantOIDs: [value] } : null,
          dataIndex: 'applicantName'
        },
        {
          id: 'currencyCode', label: messages('common.currency')/*币种*/, component: 'Selector',
          props: {
            type: 'currency',
            params: { userOId: props.user.userOID },
            filter: item => item.enable,
            showSearch: true
          },
          dataIndex: 'currencyCode'
        },
        {
          id: 'title', component: 'Input',label: messages('finance-1.key75')/*事由*/,
          props: {
            placeholder: messages('finance-1.key76')/*请输入temp2*/
          },
          dataIndex: 'title'
        },
        {
          id: 'status', label: messages('common.column.status')/*状态*/, component: (<Radio.Group>
            { this.loanStatus.map(item => <Radio key={item.value} value={item.value}>{item.label}</Radio>) }
          </Radio.Group>),
          initialValue: '10011002100310041005100610071008',
          row: true,
          decorator: {
            rules: [{ required: true }]
          },
          nullValue: '10011002100310041005100610071008',
          tagParser: value => this.loanStatus.find(item => item.value === value).label,
          dataIndex: 'status'
        }
      ],
      businessCode: '',
      sort: ''
    };
    this.handleSearch = debounce(this.handleSearch, 500);
  }

  handleSearch = businessCode => {
    this.setState({ businessCode }, () => {
      this.advancedTableRef.getList();
    })
  };

  handleRowClick = record => {
    if (record.status === 1001 && record.formType === 2005) {
      this.context.router.push(menuRoute.getRouteItem('edit-borrow').url.replace(':formOID',record.formOID).replace(':loanBillOID',record.loanBillOID));
    } else {
      openSlideFrame.openLoanReport({
        formOID: record.formOID,
        loanBillOID: record.loanBillOID,
        pathname: this.props.location.pathname
      }, {
        afterClose: value => {typeof value === 'boolean' && value && this.advancedTableRef.getList()}
      }, this);
    }
  };

  service = (page, pageSize, searchParams) => {
    const { businessCode, sort } = this.state;
    let params = { ...searchParams, businessCode };
    return borrowService.getMyLoanTable(page, pageSize, params, sort);
  };

  handleNewBorrow = (value, jobId, applicantOID, ifProxy) => {
    if (ifProxy) {
      this.context.router.push(menuRoute.getRouteItem('new-borrow').url.replace(':formOID', value).replace(':jobId', jobId).replace(':applicantOID', applicantOID).replace(':ifProxy', 1));
    } else {
      this.context.router.push(menuRoute.getRouteItem('new-borrow').url.replace(':formOID', value).replace(':jobId', jobId).replace(':applicantOID', applicantOID));
    }
  };

  importOfferFile = () => {
    this.advancedTableRef.getList();
  };

  onChangeTable = (pagination, filters, sorter) => {
    const { sort } = this.state;
    let nextSort = '';
    if(sorter.order) {
      nextSort = `${sorter.columnKey},${sorter.order === 'ascend' ? 'ASC' : 'DESC'}`
    }
    if(nextSort !== sort) {
      this.setState({ sort: nextSort }, this.advancedTableRef.getList);
    }
  };

  render() {
    const { columns, searchForm } = this.state;
    return (
      <div className='application-list full-height-page'>
        <AdvancedTable
          index
          title={messages('finance-1.key93')/*我的借款单*/}
          columns={columns}
          searchForm={searchForm}
          rowKey="loanBillOID"
          onChange={this.onChangeTable}
          expandedRowRender={record =>
            record.rejectReason ? <div>{messages('finance-1.key94')/*审批驳回*/}:{record.rejectReason}</div> : null
          }
          waterMark
          onGetDataError={e => message.error(e.response.data.message)}
          service={this.service}
          onRow={record => ({onClick: () => this.handleRowClick(record)})}
          onRef={ref => this.advancedTableRef = ref}
          tableName='my-loan'
        >
          <Space style={{ position: 'relative', display: 'flex' }}>
            <Stations formType={'104'} onOk={this.handleNewBorrow}/>
            <Proxies formType={'104'} onOk={this.handleNewBorrow}/>
            <If value={this.isNeedImporter}>
              <Importer
                btnName={messages('finance-1.key95')/*批量借款*/}
                btnProps={{type: 'default'}}
                modalOptions={{title: messages('finance-1.key95')/*批量借款*/}}
                uploadOptions={{
                  listenUrl: `/api/batch/transaction/logs/customenumerationitem`,
                  uploadUrl: '/api/loanBill/batch/uploading',
                }}
                templateOptions={{
                  templateList: [{
                    templateName: messages('finance-1.key96')/*电子表格*/,
                    downloadUrl: `/api/loanBill/template/download`
                  }]
                }}
                uploadResultOptions={{
                  shouldDownloadErrorInfo: true,
                  errorUrl: '/api/loanBill/batch/upload/error',
                  getErrorTableVisible: uploadResult => uploadResult && uploadResult.failureEntities > 0
                }}
                errorTableData={data => Importer.getUploadResult(data)}
                onOk={this.importOfferFile}
              />
            </If>
            <Search
              className="input-search input-search-left"
              placeholder={messages('finance-1.key97')/*请输入借款单号*/}
              onChange={(e) => this.handleSearch(e.target.value)}
            />
          </Space>
        </AdvancedTable>
      </div>
    )
  }
}

MyLoan.contextTypes = {
  router: React.PropTypes.object
};

function mapStateToProps(state){
  return {
    language: state.main.language,
    user: state.login.user
  }
}

export default connect(mapStateToProps)(MyLoan);
